package com.lanou.tipsy.fragment.rank;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.rank.RankInfoListAdapter;
import com.lanou.tipsy.base.BaseFragment;
import com.lanou.tipsy.base.Constants;
import com.lanou.tipsy.data.MyEventBus;
import com.lanou.tipsy.entity.playerList.personal.PersonalList;
import com.lanou.tipsy.entity.rank.rankInfor.SongListEntity;
import com.lanou.tipsy.entity.rank.rankInfor.SpecificRankResult;
import com.lanou.tipsy.entity.rank.rankInfor.rankDownload.RankInfoDownload;
import com.lanou.tipsy.tools.download.DownloadServices;
import com.lanou.tipsy.tools.downloadThread.FileDownloadThread;
import com.lanou.tipsy.tools.listview.NoScrollListView;
import com.lanou.tipsy.tools.volley.ResponseErrorListener;
import com.lanou.tipsy.tools.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.SinaShareContent;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import de.greenrobot.event.EventBus;

/**
 * Created by wangshuai on 15/10/27.
 * 排行具体页面
 */
public class RankInfoFragment extends BaseFragment
        implements View.OnClickListener, AdapterView.OnItemLongClickListener, AdapterView.OnItemClickListener {
    public static final String TAG = "RankInfoFragment";
    private ImageLoader imageLoader;
    private ImageView rankInfoIV;  //titile背景图片
    private CollapsingToolbarLayout rank_toolbar_layout;
    //网络拉取
    private VolleySingleton volleySingleton;
    private ResponseErrorListener errorListener;
    private StringRequest sq;
    private ArrayList<SongListEntity> data;//接受数据的集合
    private SongListEntity entity;
    private RankInfoListAdapter adapter;////适配器
    private NoScrollListView rankInfoLV; //榜单列表
    private TextView rankInfoNumTv; //榜单排行名字
    private Toolbar toolbar;
    private ArrayList<PersonalList> personalLists;

    /****
     * 下载
     ***/

    private static final String DOWNLOAD_TAG = FileDownloadThread.class.getSimpleName();
    //下载链接

    private PopupWindow npw;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private String downloadUrl; //歌曲下载地址
    private int count = 0;//定义下载计数器
    private String title; //歌曲名
    private String author;  //歌手
    private String songId; //歌曲id
    private String pic_url;//图片链接


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_rank_info, null);
        Share();
        return v;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //初始化方法
        init(getView());
    }

    /**
     * 邹维威干活!赶紧干活!
     * @param v
     */

    //初始化控件->添加监听
    private void init(View v) {
        //绑定布局
        rankInfoIV = (ImageView) v.findViewById(R.id.rankInfoIV); //布局上端的图片
        rank_toolbar_layout = (CollapsingToolbarLayout) v.findViewById(R.id.rank_toolbar_layout); //toolbar行布局
        rankInfoLV = (NoScrollListView) v.findViewById(R.id.rankInfoLV); //列表布局
        //添加监听
        rankInfoLV.setOnItemLongClickListener(this);
        rankInfoLV.setOnItemClickListener(this);
        rankInfoNumTv = (TextView) v.findViewById(R.id.rankInfoNumTv);
        toolbar = (Toolbar) v.findViewById(R.id.rankInfoToolbar);
        toolbar.setNavigationIcon(R.mipmap.btn_web_back_normal); //设置返回按钮
        toolbar.setNavigationOnClickListener(this);
        volleySingleton = VolleySingleton.getInstance();//队列单列
        errorListener = new ResponseErrorListener();
        //接受数据
        Bundle bundle = getArguments();
        String rankUrl = (String) bundle.get("songUrl");
        String name = bundle.getString("name");
        int type = bundle.getInt("type");
        /** volley进行网络图片的获取 */
        imageLoader = VolleySingleton.getInstance().getImageLoader();
        ImageLoader.ImageListener imageListener = ImageLoader.getImageListener
                (rankInfoIV, R.mipmap.logo_2, R.mipmap.error);
        imageLoader.get(rankUrl, imageListener);
        rankInfoIV.setImageURI(Uri.parse(rankUrl));
        //toolbar 内添加数据
        rank_toolbar_layout.setTitle(name);
        //进行url 拼接
        String url = Constants.RANK_INFO_START + type + Constants.RANK_INFO_END;
        sq = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //日志打印,查看数据是否能够得到,是否能进行下一步的gson解析
                Log.i("test", "RankInfoFragment" + response);
                Gson gson = new Gson();
                SpecificRankResult specificRankResult = gson.fromJson(response, SpecificRankResult.class);
                data = specificRankResult.getSong_list();
                adapter = new RankInfoListAdapter(getContext(), data);
                rankInfoLV.setAdapter(adapter);
                rankInfoNumTv.setText("共" + data.size() + "首歌");
            }
        }, errorListener);

        //绑定队列
        //queue.add(sq);
        volleySingleton.addQueue(sq, TAG);
    }

    //返回点击
    @Override
    public void onClick(View v) {
        getActivity().getSupportFragmentManager().popBackStack();
    }

    //行布局长按监听,实现弹出popupwindow,并内部添加收藏,下载,分享功能
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        //数据获取
        title = data.get(position).getTitle();
        author = data.get(position).getAuthor();
        songId = data.get(position).getSong_id();
        Log.i("lanou", title + "  " + author);
        final PopupWindow pw = new PopupWindow(getContext());
        // 通过布局加载器加载布局文件
        View view1 = getLayoutInflater(getArguments()).inflate(R.layout.popup_window_rankinfo,
                null);
        //取消按钮
        Button rankCancelBtn = (Button) view1.findViewById(R.id.rankCancelBtn);
        ImageButton rankCollectIBtn = (ImageButton) view1.findViewById(R.id.rankCollectIBtn);
        ImageButton rankDownloadIBtn = (ImageButton) view1.findViewById(R.id.rankDownloadIBtn);
        ImageButton rankShareIBtn = (ImageButton) view1.findViewById(R.id.rankShareIBtn);

        TextView rankPWTv = (TextView) view1.findViewById(R.id.rankPWTv);
        rankPWTv.setText(title);
        //收藏的监听
        rankCollectIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });

        //下载的监听
        rankDownloadIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;//每日点击就计数累加一次

                // 获取SD卡路径
                String path = Environment.getExternalStorageDirectory()
                        + "/amosdownload/";
                File file = new File(path);
                // 如果SD卡目录不存在创建
                if (!file.exists()) {
                    file.mkdir();
                }
                String url = Constants.RANK_INFO_DOWN_START + songId +  Constants.RANK_INFO_DOWN_END;
                JsonObjectRequest jr = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        String str = response.toString();
                        RankInfoDownload link = JSON.parseObject(str, RankInfoDownload.class);
                        if (link.getSongurl().getUrl().get(0).getShow_link() != null) {
                            downloadUrl = link.getSongurl().getUrl().get(0).getShow_link();
                            pic_url = link.getSonginfo().getPic_small();
                            startDownloadService(count, downloadUrl, title,pic_url);
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
                //添加队列
                volleySingleton.addQueue(jr, TAG);
            }
        });
        //分享 的监听
        rankShareIBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("shareButton","点击");
                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                // 是否只有已登录用户才能打开分享选择页
                mController.openShare(getActivity(), false);
                share();
            }
            private void share(){
                SinaShareContent sinaShareContent = new SinaShareContent();
                sinaShareContent.setTitle("测试");
                sinaShareContent.setShareContent("内容");
                sinaShareContent.setTargetUrl("分享链接");
                mController.setShareMedia(sinaShareContent);
            }
        });
        /**
         *  popupwindow属性设置
         */
        //设置SelectPicPopupWindow的View
        pw.setContentView(view1);
        //设置SelectPicPopupWindow弹出窗体的宽
        pw.setWidth(ViewGroup.LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        pw.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        pw.setFocusable(true);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        pw.setBackgroundDrawable(dw);
        //产生背景变暗效果
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.6f;
        getActivity().getWindow().setAttributes(lp);
        //显示窗口,设置layout在PopupWindow中显示的位置
        pw.showAtLocation(getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        //取消按钮的监听
        rankCancelBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                pw.dismiss();
            }
        });
        //窗口消失时候回复的监听方法
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });


        return true;
    }

    //下载服务方法 两个参数,通知栏的id , 下载的链接
    public void startDownloadService(int notifyId, String url, String title, String pic_url) {
        //绑定服务类
        Intent i = new Intent(getContext(), DownloadServices.class);
        //传值
        i.putExtra("pic_url",pic_url);
        i.putExtra("title", title);
        i.putExtra("url", url);
        i.putExtra("notifyId", notifyId);
        //服务启动
        getActivity().startService(i);
    }

    /**
     * 分享
     */
    private void Share(){
        SinaShareContent sinaShareContent = new SinaShareContent();
        sinaShareContent.setTitle(title);
        sinaShareContent.setShareContent("内容");
        sinaShareContent.setTargetUrl(pic_url);
        mController.setShareMedia(sinaShareContent);
    }

    //listview行布局点击监听->播放歌曲
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        entity = (SongListEntity) parent.getItemAtPosition(position);
        Log.i("test", "RankInfoFragment->点击行布局监听->position:" + position + ",歌曲名:" + entity.getTitle());
        personalLists = new ArrayList<>();
        for (SongListEntity songListEntity : data) {
            PersonalList personalList = new PersonalList();
            personalList.setSingerName(songListEntity.getAuthor());
            personalList.setSongsUrl(songListEntity.getSong_id());
            personalList.setTag("网络歌曲");
            personalList.setSongTitle(songListEntity.getTitle());
            personalList.setPicture(songListEntity.getPic_big());
            personalLists.add(personalList);
        }
        //发送数据到EventBus
        EventBus.getDefault().post(new MyEventBus.NetSongs(personalLists, position));
    }

    @Override
    public void onStop() {
        super.onStop();
        volleySingleton.removeRequest(TAG);
    }
}
